package controller

import (
	"ez/apps/core/auto/controller"
	core "ez/apps/core/document"
	"ez/config/r"
	"ez/custom/cc"
	"gitee.com/dreamwood/ez-go/ez"
	"gitee.com/dreamwood/ez-go/ss"
	"strings"
)

type ApiController struct {
	controller.ApiAutoController
}

func init() {
	c := &ApiController{}
	ez.CreateApi(r.AdminGet("Api"), c.GetAction)
	ez.CreateApi(r.AdminList("Api"), c.ListAction)
	ez.CreateApi(r.AdminSave("Api"), c.SaveAction)
	ez.CreateApi(r.AdminCopy("Api"), c.CopyAction)
	ez.CreateApi(r.AdminTree("Api"), c.TreeAction)
	ez.CreateApi(r.AdminUpdate("Api"), c.UpdateAction)
	ez.CreateApi(r.AdminChoice("Api"), c.ChoiceAction)
	ez.CreateApi(r.AdminDelete("Api"), c.DeleteAction)
	ez.CreateApi(r.AdminUnDelete("Api"), c.UnDeleteAction)
	ez.CreateApi(r.AdminDestroy("Api"), c.DestroyAction)
	ez.CreateApi(r.AdminUpdateMany("Api"), c.UpdateManyAction)
	ez.CreateApi(r.AdminDeleteMany("Api"), c.DeleteManyAction)
	ez.CreateApi(r.AdminDestroyMany("Api"), c.DestroyManyAction)
	ez.CreateApi(r.AdminTree("Api"), c.TreeAction)
	ez.CreateApi(r.AdminApi("/Api/group"), c.GroupAction)
}

// func (c ApiController) AccessControl(session *ez.Session) { /* 在这里面重构 */ }
// func (c ApiController) GetAction(session *ez.Session) { /* 在这里面重构 */ }
// func (c ApiController) ListAction(session *ez.Session) { /* 在这里面重构 */ }
func (c ApiController) GroupAction(session *ez.Session) {
	this := cc.New(session)
	crud := core.NewApiCrud()
	all, _ := crud.FindBy(ss.M{}, []string{"id"}, 0, 0)
	for _, api := range all {
		findOrCreateApiParent(api)
	}
	core.ApiTreeModel{}.UpdateLeftAndRight(0, 0, 0)
	this.ReturnSuccess("OK", "")

}

func findOrCreateApiParent(api *core.Api) {
	crud := core.NewApiCrud()
	split := strings.Split(api.Route, "/")
	if len(split) < 2 {
		return
	}
	parentRout := strings.Join(split[:len(split)-1], "/")
	find, _ := crud.FindOneBy(ss.M{"route": parentRout}, []string{"id"})
	if find.Id == 0 {
		find.App = api.App
		find.Route = parentRout
		find.Save()
		findOrCreateApiParent(find)
	}
	api.ParentId = find.Id
	api.Save()

}
